package com.example.administrator.shzs.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.example.administrator.shzs.R;
import com.example.administrator.shzs.activity.BaseActivity;
import com.example.administrator.shzs.adapter.ShippingAddressAdapter;
import com.example.administrator.shzs.app.MyApplication;
import com.example.administrator.shzs.url.Contents;
import com.example.administrator.shzs.entity.UserAddressData.AddressData;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 收货地址页面
 */
public class  ShippingAddressActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.iv_back_shipping_adderss_activity)
    ImageView ivBack;
    @Bind(R.id.mXrecyclerView_shipping_address_activity)
    XRecyclerView mXrecyclerView;
    @Bind(R.id.ll_shopping_address)
    LinearLayout llShippingAddress;

    private double latitude;
    private double longitude;


    /**
     * 用户ID
     */
    private String userid;

    private List<AddressData> addressDatas;

    private ShippingAddressAdapter adapter;
    private Context ctx;

    /**
     * 是否是从订单页面跳转过来的，默认不是
     */
    private boolean IsOrderActivity=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shipping_address);
        ButterKnife.bind(this);
        MyApplication.app.activityList.add(this);
        ctx=this;
        //初始化
        setViews();

        getData();
        //监听器
        steListeners();


    }

    /**
     * 获取数据
     */
    private void getData() {
        latitude= MyApplication.app.getLatitude();//纬度
        longitude=MyApplication.app.getLongitude();//经度

        userid = MyApplication.app.getUserId();
        getAddressDataFormServer(userid);

        Intent intent = getIntent();//标记是从订单界面跳转过来的
        IsOrderActivity=intent.getBooleanExtra("selectAddress",false);
    }

    /**
     * 获取地址列表
     * @param userid
     */
    private void getAddressDataFormServer(String userid) {

        String url= Contents.USER_ADDRESS_LISTING+userid;

        RequestParams params=new RequestParams(url);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                try {

                    JSONObject object=new JSONObject(result);
                    JSONArray array = object.getJSONArray("list");
                    addressDatas=JSON.parseArray(array.toString(),AddressData.class);
                    setAdapter();


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });
    }

    /**
     * 适配器
     */
    private void setAdapter() {

        adapter=new ShippingAddressAdapter(this,addressDatas);
        mXrecyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new ShippingAddressAdapter.OnRecyclerViewItemClickListener() {

            @Override
            public void onItemClick(View view, String name, String address, String phone) {

                if(IsOrderActivity){//如果是从订单页面跳转过来的,允许点击
                    Intent intent=getIntent();
                    intent.putExtra("name",name);
                    intent.putExtra("address",address);
                    intent.putExtra("phone",phone);
                    setResult(RESULT_OK,intent);
                    finish();
                }
            }

            @Override
            public void onDeleteClick(final ShippingAddressAdapter.MyViewHolder holder, String name, String address, String phone, String dataId) {

                //删除地址
                deleteAddress(holder,name,address,phone,dataId);
            }


            @Override
            public void onCompileClick(ShippingAddressAdapter.MyViewHolder holder, String name, String address, String phone, String dataId) {

                compileAddress(holder,name,address,phone,dataId);
            }
        });

    }

    /**
     * 编辑<修改>地址
     * @param holder
     * @param name
     * @param address
     * @param phone
     * @param dataId
     */
    private void compileAddress(final ShippingAddressAdapter.MyViewHolder holder, String name, String address, String phone, String dataId) {


        Intent intent=new Intent(this,CompileAddressActivity.class);
        Bundle bundle=new Bundle();
        bundle.putString("name",name);
        bundle.putString("address",address);
        bundle.putString("phone",phone);
        bundle.putString("dataId",dataId);
        bundle.putString("userid",userid);
        bundle.putDouble("longitude",longitude);
        bundle.putDouble("latitude",latitude);
        intent.putExtras(bundle);
        startActivityForResult(intent,REQUEST_CODE_COMPILE_ADDRESS);
//        overridePendingTransition(R.anim.slide_in_left,R.anim.slide_in_left);

    }

    /**
     * 删除地址
     * @param holder
     * @param name
     * @param address
     * @param phone
     * @param dataId
     */
    private void deleteAddress(final ShippingAddressAdapter.MyViewHolder holder, String name, String address, String phone, String dataId) {

        String url= Contents.USER_NEW_ADD_USER_SHIPPING_ADDRESS;

        RequestParams params=new RequestParams(url);
        params.addBodyParameter("receiver",name);
        params.addBodyParameter("address",address);
        params.addBodyParameter("mobilephone",phone);
        params.addBodyParameter("userid",userid);
        params.addBodyParameter("dataid",dataId);
        params.addBodyParameter("lng",longitude+"");
        params.addBodyParameter("lat",latitude+"");
        params.addBodyParameter("op","-1");

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Log.i("","*******************删除"+result);
                try {

                    JSONObject object =new JSONObject(result);
                    int state = object.getInt("state");
                    if(state==1){
                        adapter.removeData(holder.getAdapterPosition());
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });

    }


    /**
     * 初始化
     */
    private void setViews() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mXrecyclerView.setLayoutManager(manager);

        mXrecyclerView.setRefreshing(true);
        mXrecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mXrecyclerView.setLoadingMoreProgressStyle(ProgressStyle.SquareSpin);
        //刷新箭头
        mXrecyclerView.setArrowImageView(R.mipmap.ic_pulltorefresh_arrow);

        mXrecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mXrecyclerView.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                mXrecyclerView.loadMoreComplete();
            }
        });


    }

    /**
     * 监听
     */
    private void steListeners() {
        ivBack.setOnClickListener(this);
        llShippingAddress.setOnClickListener(this);
    }

    /**
     * 保存地址
     */
    private static final int REQUEST_CODE_SAVE_ADDRESS = 1;

    /**
     * 编辑地址
     */
    private static final int REQUEST_CODE_COMPILE_ADDRESS = 2;

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.iv_back_shipping_adderss_activity://返回

                finish();

                break;

            case R.id.ll_shopping_address://新增收货地址
                Intent intent=new Intent(new Intent(this,NewAddAddressActivity.class));
                startActivityForResult(intent,REQUEST_CODE_SAVE_ADDRESS);
                break;

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode){

            case REQUEST_CODE_SAVE_ADDRESS:

                if(resultCode== Activity.RESULT_OK){
                    getAddressDataFormServer(userid);
                }

                break;

            case REQUEST_CODE_COMPILE_ADDRESS:

                if(resultCode==Activity.RESULT_OK){
                    getAddressDataFormServer(userid);
                }

                break;
        }
    }
}
